var imgNo = "<img width='15px' src='images/n.png'/>";
var imgYes = "<img width='15px' src='images/y.png'>";

function validateTip(element,css,tipString,status){
    element.css(css);
    element.html(tipString);
    element.attr("validateStatus",status);
}
$(function () {

    var l1 = $("#L1");
    var l2 = $("#L2");
    var l3 = $("#L3");

    var name = $("#name");
    var price = $("#price");
    var stock = $("#stock");
    var desc = $("#description");
    var file = $("#fileName");
    var pid = $("#productId");
    var add = $("#add");
    var form = $("#productForm");
    var t1 = $("#t1");
    var t2 = $("#t2");
    var t3 = $("#t3");
    var t4 = $("#t4");
    var t5 = $("#t5");
    var tl1 = $("#TL1");
    var tl2 = $("#TL2");
    var tl3 = $("#TL3");

    var img = document.getElementById("fileName");

    l1.change(function () {
        fillL2();
        fillL3();
    });
    l2.change(function () {
        fillL3();
    });

    function fillL2(){
        var pcode = l1.val();
        $.ajax({
            async : false,
            url : "easybuy/product/getType",
            data : {"id":pcode},
            type : "post",
            dataType: "json",
            success : function (data) {
                var str = "";
                l2.html("");
                for(var i=0;i<data.length;i++){
                    str += "<option value='"+data[i].id+"'>"+data[i].name+"</option>"
                }
                l2.append(str);
            }
        });

    }
    function fillL3(){
        var pcode = l2.val();
        $.ajax({
            async : false,
            url : "easybuy/product/getType",
            data : {"id":pcode},
            type : "post",
            dataType: "json",
            success : function (data) {
                var str = "";
                l3.html("");
                for(var i=0 ; i<data.length; i++){
                    str += "<option value='"+data[i].id+"'>"+data[i].name+"</option>"
                }
                l3.append(str);
            }
        });

    }

    l1.bind("blur",function () {
       if(l1.val()==0){
           validateTip(tl1,{"color":"red"}, imgNo+" * 请选择一级分类",false);
       }else {
           validateTip(tl1,{"color":"red"}, imgYes,true);
       }
    });

    l2.bind("blur",function () {
        if(l2.val()==0){
            validateTip(tl2,{"color":"red"}, imgNo+" * 请选择二级分类",false);
        }else {
            validateTip(tl2,{"color":"red"}, imgYes,true);
        }
    });

    l3.bind("blur",function () {
        if(l3.val()==0){
            validateTip(tl3,{"color":"red"}, imgNo+" * 请选择三级分类",false);
        }else {
            validateTip(tl3,{"color":"red"}, imgYes,true);
        }
    });

    name.bind("focus",function () {
        validateTip(t1,{"color": "red"}, " * 请输入不超过20个字符", false)
    }).bind("blur",function () {
        if(name.val() == null || name.val()==""){
            validateTip(t1,{"color":"red"}, imgNo+" * 商品名称不能为空",false);
        }else if(name.val().length>20){
            validateTip(t1,{"color":"red"}, imgNo+" * 商品名称过长，请控制在20字符以内",false);
        }else {
            validateTip(t1,{"color":"green"},imgYes,true);
        }
    });

    price.bind("focus",function () {
        validateTip(t3,{"color":"red"}, " * 单价不能小于0",false);
    }).bind("blur",function () {
        if(price.val() == null || price.val() ==""){
            validateTip(t3,{"color":"red"},imgNo+" * 请输入单价",false);
        }else if(price.val()<0 || price.val()>10000000 || isNaN(price.val())){
            validateTip(t3,{"color":"red"},imgNo+" * 单价范围错误",false);
        }else {
            validateTip(t3,{"color":"green"},imgYes,true);
        }
    });

    stock.bind("focus",function () {
        validateTip(t4,{"color":"red"}," * 请输入正整数",false);
    }).bind("blur",function () {
        var re = /^\d*$/;
        if(stock.val() ==null || stock.val()==""){
            validateTip(t4,{"color":"red"},imgNo+ " * 请输入库存数量",false)
        }else if(!re.test(stock.val()) || isNaN(stock.val())){
            validateTip(t4, {"color":"red"}, imgNo + " * 请输入正确的数字",false);
        }else{
            validateTip(t4,{"color":"green"}, imgYes, true);
        }

    });

    desc.bind("blur",function () {
        if(desc.val()>3000){
            validateTip(t5,{"color":"red"}, imgNo + " * 输入内容过长",false);
        }else{
            validateTip(t5,{"color":"red"}, imgYes ,true);
        }

    });

    file.bind("click",function () {
        validateTip(t2,{"color":"red"},imgNo + " * 请上传商品图片",false);
    }).bind("blur",function () {
        var animateimg = $("#fileName").val();  //获取上传的图片名 带//
        var imgarr=animateimg.split('\\');      //分割
        var myimg=imgarr[imgarr.length-1]; //去掉 // 获取图片名
        var houzui = myimg.lastIndexOf('.'); //获取 . 出现的位置
        var ext = myimg.substring(houzui, myimg.length).toUpperCase();  //切割 . 获取文件后缀

        //var files = $('#fileName').get(0).files[0]; //获取上传的文件
        var fileSize = $("#fileName")[0].files[0].size;          //获取上传的文件大小
        var maxSize = 1048576;              //最大1MB
        if(ext !='.PNG' && ext !='.GIF' && ext !='.JPG' && ext !='.JPEG' && ext !='.BMP'){
            t2.html("");
            validateTip(t2,{"color":"red"},imgNo + " * 文件类型错误,请上传图片类型",false);
            //parent.layer.msg('文件类型错误,请上传图片类型');
            //return false;
        }else if(parseInt(fileSize) >= parseInt(maxSize)) {
            validateTip(t2,{"color":"red"},imgNo + " * 上传的文件不能超过1MB",false);
            //parent.layer.msg('上传的文件不能超过1MB');
            //return false;

        }else if(animateimg=="" || animateimg==null){
           t2.html("");
           validateTip(t2,{"color":"red"},imgNo + " * 请上传商品图片",false);
        }else{
           validateTip(t2,{"color":"red"},imgYes,true);
       }
    });


    function getObjectURL(file) {
        var url = null ;
        if (window.createObjectURL!=undefined) { // basic
            url = window.createObjectURL(file) ;
        } else if (window.URL!=undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file) ;
        } else if (window.webkitURL!=undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file) ;
        }
        return url ;
    }

    file.on("change",function(){
        var objUrl = getObjectURL(this.files[0]) ; //获取图片的路径，该路径不是图片在本地的路径
        if (objUrl) {
            $("#img").attr("src", objUrl) ; //将图片路径存入src中，显示出图片
        }
    });

    add.click(function () {

        var imgurl = file.val();
        var formDate = new FormData();

        var uploadFile = img.files[0];

        formDate.append("fileName",uploadFile);
        formDate.append("categoryLevel1Id",l1.val());
        formDate.append("categoryLevel2Id",l2.val());
        formDate.append("categoryLevel3Id",l3.val());
        formDate.append("name",name.val());
        formDate.append("price",price.val());
        formDate.append("stock",stock.val());
        formDate.append("description",desc.val());

        if(t1.attr("validateStatus") != "true" ){
            name.blur();
        }else if(t3.attr("validateStatus") != "true"){
            price.blur();
        }else if(t4.attr("validateStatus") != "true"){
            stock.blur();
        }else if(t5.attr("validateStatus") != "true"){
            desc.blur();
        }else if(tl1.attr("validateStatus") != "true"){
            l1.blur();
        }else if(tl2.attr("validateStatus") != "true"){
            l2.blur();
        }else if(tl3.attr("validateStatus") != "true"){
            l3.blur();
        }else if("undefined" == typeof(file) || file == null || file == ""){
            file.blur();
        }
        else {
            if("undefined" != typeof(file) && file != null && file != ""){
                console.log(file);
                if(confirm("确认提交")){
                    $.ajax({
                        url : "easybuy/product/addProduct",
                        type : "POST",
                        data : formDate,
                        async : false,
                        cache : false,
                        contentType : false,
                        processData: false,
                        success : function(data){
                            if(data.uploadFileError !=null ){
                                alert("上传失败");
                                validateTip(t2,{"color":"red"},imgNo + " * 上传失败",false);
                            }
                            if(data.add = "success"){
                                alert("新增成功");
                                window.location.href = "Product_admin.html";
                            }
                        },
                        error : function (XMLHttpRequest, textStatus, errorThrown) {
                            alert("出现错误");
                            console.log(XMLHttpRequest.status);
                            console.log(XMLHttpRequest.readyState);
                            console.log(textStatus);
                            //alert(XMLHttpRequest.status);
                            //alert(XMLHttpRequest.readyState);
                            //alert(textStatus);
                        },complete: function(XMLHttpRequest, textStatus) {
                            this; // 调用本次AJAX请求时传递的options参数
                        }

                    });
                }else {
                    alert("文件类型错误，请重新选择");
                }
            }

        }

    });

});